package com.yexx.starter.security.basic;

import com.yexx.core.exception.CommonException;
import com.yexx.starter.security.basic.constant.SecurityConstants;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Description: 最外层filter处理验证token、登录认证和授权过滤器中抛出的所有异常
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/02-14:29
 */
public class BasicExceptionHandleFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
            Integer code = SecurityConstants.RETURN_CODE.SYS_ERROR;
            if (e instanceof CommonException) {
                CommonException ex = (CommonException) e;
                code = ex.getCode();
            }
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            try (PrintWriter out = response.getWriter()) {
                out.write(String.format(SecurityConstants.RETURN_JSON.DYNAMIC_CODE, code, e.getMessage()));
                out.flush();
            }
        }
    }
}
